import * as signalr from "@microsoft/signalr";
import { ElNotification } from 'element-plus'
import config from "../config";




export default {
    SR: {},
    failNum: 4,//失败重试次数
    baseUrl: '',


    //初始化连接
    init() {
        console.log('signalR初始化连接');

        var socketUrl = config.signalRUrl
        const connection = new signalr.HubConnectionBuilder()
            .withUrl(socketUrl)
            .withAutomaticReconnect()
            .configureLogging(signalr.LogLevel.Warning)
            .build();

        this.SR = connection

        //失败重连
        connection.onclose(async () => {
            console.log('断开连接')
            //断言连接状态
            console.assert(connection.state === signalr.HubConnectionState.Disconnected)
            await this.start();
        })

        connection.onreconnecting(() => {
            console.log('正在重连')
        })

        //接收消息处理
        this.receiveMsg(connection);
    },
    //开启连接
    async start() {
        console.log('signalR开始连接');

        var that = this

        try {
            await this.SR.start()
            console.log('signalR连接成功');
            console.log('signalR', this.SR.state);
            return true;
        } catch (error) {
            that.failNum--;
            if (that.failNum > 0 && this.SR.state.Disconnected) {
                setTimeout(async () => {
                    console.log(`失败，正在重试第${that.failNum}次`);
                    await this.SR.start()
                }, 5000);//5s重试间隔
            }
            console.log('signalR连接失败');
            return false;
        }
    },
    //接收消息处理
    receiveMsg(connection) {
        connection.on("OnlineUserList", (data) => {
            var count = data.length
            console.log('当前在线人数' + count);
        });
    }
}